package com.fengmi.html.mq;


import com.fengmi.api.goods.GoodsApi;
import com.fengmi.goods.MallGoods;
import com.fengmi.html.bean.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.SneakyThrows;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RocketMQMessageListener(consumerGroup = "fengmi-goods-html-consumer",
        topic = "goods-html",selectorExpression = "audit",
        consumeMode = ConsumeMode.CONCURRENTLY,
        messageModel = MessageModel.CLUSTERING)
public class GenHtml implements RocketMQListener<String> {
   @Autowired
    FreeMarkerConfig freeMarkerConfig;
   @Autowired
   GoodsApi goodsApi;
    @Override
    public void onMessage(String spuId) {
        System.out.println("收到生成静态页面的消息商品id为:"+spuId);
        //生成静态页面
        Configuration configuration = freeMarkerConfig.getConfiguration();
        //获取模板对象
        Template template = null;
        try {
            MallGoods goodsAndSku = goodsApi.getGoodsAndSku(Long.valueOf(spuId));
            template = configuration.getTemplate("introduction.ftl");
            Map map = new HashMap();
//            private  String name; //口味，或 包装
//            private List<String> opts; //具体口味或具体包装
            map.put("spus",goodsAndSku.getSpus());   // [{"name":"口味","opts":["原味","咸香"]},{"name":"包装","opts":["情侣装","全家福"]}]
            map.put("skuList",goodsAndSku.getSkuList());
            map.put("spuId",spuId);
            //指定静态文件路径及名称
            FileWriter fileWriter = new FileWriter("D:\\softin\\nginx\\nginx-1.18.0\\pages\\"+spuId+".html");
            //生成静态文件
            template.process(map,fileWriter);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

    }
}
